/*
 * @lc app=leetcode.cn id=110 lang=javascript
 *
 * [110] 平衡二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    return balanced(root) != -1;
    //若不满足平衡二叉树则返回-1,满足条件则返回二叉树的深度
};

var balanced = function(node) {
    if(!node) return 0;
    //空二叉树是平衡二叉树
    let left = balanced(node.left);
    let right = balanced(node.right);
    if(left == -1 || right == -1 || Math.abs(left-right)>1) {
        return -1
        //判断左子树不平衡或者右子树不平衡或当前树左右结点高度大于1都不满足平衡二叉树的条件
    }
    return Math.max(left,right)+1
    //如果左右高度差不大于1则返回树的深度
}
// @lc code=end

